package com.awei.project.controller;

import com.awei.project.cos.COSoperate;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.awei.project.common.BaseResponse;
import com.awei.project.common.DeleteRequest;
import com.awei.project.common.ErrorCode;
import com.awei.project.common.ResultUtils;
import com.awei.project.exception.BusinessException;
import com.awei.project.model.dto.userRequest.*;
import com.awei.project.model.entity.User;
import com.awei.project.model.vo.UserVO;
import com.awei.project.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.awei.project.constant.UserConstant.SALT;

/**
 * 用户接口
 *
 * @author 小维哥
 * @version 1.2
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
        @Resource
        private UserService userService;

        @Resource
        private RedisTemplate<String, Object> redisTemplate;
        // region 登录相关

        /**
         * 用户注册
         */
        @ApiOperation("用户注册")
        @PostMapping("/register")
        public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
                if (userRegisterRequest == null) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                String userAccount = userRegisterRequest.getUserAccount();
                String userPassword = userRegisterRequest.getUserPassword();
                String checkPassword = userRegisterRequest.getCheckPassword();
                if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                long result = userService.userRegister(userRegisterRequest);
                return ResultUtils.success(result);
        }

        /**
         * 用户登录
         */
        @ApiOperation("用户登录")
        @PostMapping("/login")
        public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
                if (userLoginRequest == null) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                String userAccount = userLoginRequest.getUserAccount();
                String userPassword = userLoginRequest.getUserPassword();
                if (StringUtils.isAnyBlank(userAccount, userPassword)) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                User user = userService.userLogin(userAccount, userPassword, request);
                return ResultUtils.success(user);
        }

        /**
         * 用户注销
         */
        @ApiOperation("用户退出")
        @PostMapping("/logout")
        public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
                if (request == null) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                boolean result = userService.userLogout(request);
                return ResultUtils.success(result);
        }

        /**
         * 获取当前登录用户
         */
        @ApiOperation("获取当前登录用户")
        @GetMapping("/current")
        public BaseResponse<UserVO> getLoginUser(HttpServletRequest request) {
                User user = userService.getLoginUser(request);
                UserVO userVO = new UserVO();
                BeanUtils.copyProperties(user, userVO);
                return ResultUtils.success(userVO);
        }

        // endregion

        // region 增删改查
        /**
         * 创建用户
         */
        //todo 每次添加id不知道为啥这么大
        @ApiOperation("用户添加(管理员使用)")
        @PostMapping("/add")
        public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
                if (userAddRequest == null) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                User user = new User();
                BeanUtils.copyProperties(userAddRequest, user);
                //密码加密
                String password = DigestUtils.md5DigestAsHex((SALT + user.getUserPassword()).getBytes());
                user.setUserPassword(password);
                //添加
                boolean result = userService.save(user);
                if (!result && userService.isAdmin(user)) {
                        throw new BusinessException(ErrorCode.OPERATION_ERROR);
                }
                return ResultUtils.success(user.getId());
        }

        /**
         * 删除用户
         */
        @ApiOperation("用户根据id进行逻辑删除")
        @PostMapping("/delete")
        public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
                if (deleteRequest == null || deleteRequest.getId() <= 0) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                boolean b = userService.removeById(deleteRequest.getId());
                return ResultUtils.success(b);
        }

        /**
         * 更新用户
         */
        @ApiOperation("用户根据id进行更新")
        @PostMapping("/update")
        public BaseResponse<Integer> updateUser(@RequestBody User user, HttpServletRequest request) {
                if (user == null || user.getId() == null) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                User loginUser = userService.getLoginUser(request);
                Integer result = userService.updateUserById(user, loginUser);
                return ResultUtils.success(result);
        }

        //todo 可以进行优化的点：2分钟内，若反复传入相同的图片？怎么办？后端加修改头像的间隔时间？
        /**
         * 更新用户的头像，并存储到腾讯云的cos中
         * @param file 头像内容
         * @param request
         * @return
         */
        @ApiOperation("用户根修改自己的头像")
        @PostMapping("/updateImg")
        public BaseResponse<Boolean> updateUserImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
                if (file.isEmpty()) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                User loginUser = userService.getLoginUser(request);
                boolean result = userService.updateUserImg(file, loginUser);
                return ResultUtils.success(result);
        }
        /**
         * 根据 id 获取用户
         */
        @ApiOperation("用户根据id进行获取")
        @GetMapping("/get")
        public BaseResponse<UserVO> getUserById(int id) {
                if (id <= 0) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                User user = userService.getById(id);
                UserVO userVO = new UserVO();
                BeanUtils.copyProperties(user, userVO);
                return ResultUtils.success(userVO);
        }

        /**
         * 获取用户列表
         */
        @ApiOperation("用户根据条件直接获取所有用户")
        @GetMapping("/list")
        public BaseResponse<List<UserVO>> listUser(UserQueryRequest userQueryRequest) {
                User userQuery = new User();
                if (userQueryRequest != null) {
                        BeanUtils.copyProperties(userQueryRequest, userQuery);
                }
                QueryWrapper<User> queryWrapper = new QueryWrapper<>(userQuery);
                List<User> userList = userService.list(queryWrapper);
                List<UserVO> userVOList = userList.stream().map(user -> {
                        UserVO userVO = new UserVO();
                        BeanUtils.copyProperties(user, userVO);
                        return userVO;
                }).collect(Collectors.toList());
                return ResultUtils.success(userVOList);
        }

        /**
         * 分页获取用户列表
         */
        @ApiOperation("用户 条件分页查询(首页面)")
        @GetMapping("/list/page")
        public BaseResponse<Page<UserVO>> listUserByPage(UserQueryRequest userQueryRequest) {
                long current = 1;
                long size = 10;
                if (userQueryRequest == null) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                Page<UserVO> userVOPage = userService.listUserByPage(userQueryRequest, size, current);
                return ResultUtils.success(userVOPage);
        }

        /**
         *  根据标签搜索用户
         * @param tagNameList
         * @return
         */
        @ApiOperation("根据标签搜索用户")
        @GetMapping("/search/tags")
        public BaseResponse<List<User>> SearchUsersByTags(@RequestParam(required = false) List<String> tagNameList) {
                if (CollectionUtils.isEmpty(tagNameList)) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                int current = 1;
                int size = 10;
                List<User> userList = userService.searcherUserByTags(tagNameList, size, current);
                return ResultUtils.success(userList);
        }
        /**
         * 搜索用户
         * @param username
         * @param request
         * @return
         */
        @GetMapping("/search")
        public BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request) {
                if (!userService.isAdmin(request)) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                if (StringUtils.isNotBlank(username)) {
                        queryWrapper.like("username", username);
                }
                List<User> userList = userService.list(queryWrapper);
                List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
                return ResultUtils.success(list);
        }

        // endregion

        /**
         * 用户修改标签
         * @param userUpdateTagsRequest
         * @param request
         * @return
         */
        @PostMapping("/updateTags")
        public BaseResponse<Integer> updateTags(@RequestBody UserUpdateTagsRequest userUpdateTagsRequest, HttpServletRequest request){
                //校验参数是否为空
                if (userUpdateTagsRequest == null){
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                //修改者的id
                Long userId = userUpdateTagsRequest.getId();
                //修改者的标签
                List<String> tags = userUpdateTagsRequest.getTags();
                //校验权限（需要拿到当前用户的用户登录态）
                User loginUser = userService.getLoginUser(request);
                //触发更新
                int result = userService.updateTags(userId, loginUser, tags);
                return ResultUtils.success(result);
        }

        //获取最佳匹配用户
        @GetMapping("/match")
        public BaseResponse<List<User>> matchUsers(long pageSize, long pageNum, HttpServletRequest request) {
                if (pageSize <= 0 || pageSize > 10) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR);
                }
                if(pageNum!=1){
                        throw new BusinessException(ErrorCode.OPERATION_ERROR,"暂时仅推荐五位用户");
                }
                User user = userService.getLoginUser(request);
                return ResultUtils.success(userService.matchUsers(pageSize, user));
        }

        // 随机获取/pageNum==current
        @GetMapping("/recommend")
        public BaseResponse<Page<User>> recommendUsers(long pageSize, long pageNum, HttpServletRequest request) {
                User loginUser = userService.getLoginUser(request);
                String redisKey;
                redisKey = String.format("aweipipei:user:recommend:%s:%s", loginUser.getId(),pageNum);
                ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
                // 如果有缓存，直接读缓存
                Page<User> userPage = (Page<User>) valueOperations.get(redisKey);
                if (userPage != null) {
                        return ResultUtils.success(userPage);
                }
                // 无缓存，查数据库
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                userPage = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
                // 写缓存
                try {
                        valueOperations.set(redisKey, userPage, 30000, TimeUnit.MILLISECONDS);
                } catch (Exception e) {
                        log.error("redis set key error", e);
                }
                return ResultUtils.success(userPage);
        }
}
